#coding:utf-8
# 将tcp读取到的温度数据，使用websocket服务提供给网页读取

from tornado import web, websocket
from tornado import ioloop, gen, iostream
from tornado.tcpclient import TCPClient
import time

HOST = '127.0.0.1'  # 温度服务ip地址
PORT = 9999         # 温度服务通信端口号
LISTEN_PORT = 9099  # 数据提供服务监听端口

data = b""

# TCP 数据读取
@gen.coroutine
def Trans():
    global data
    stream = yield TCPClient().connect(HOST, PORT)
    try:
        while True:
            data = yield stream.read_bytes(20, partial=True)
            print("data: ", data.decode("utf-8"))

    except iostream.StreamClosedError:
        data = b""

# WebSocket服务提供
class WebSocketHandler(websocket.WebSocketHandler):
    def check_origin(self, origin: str) -> bool:
        return True

    def open(self):
        print("open success")
        # 定时器，每秒向前端发送一次数据
        self.timer = ioloop.PeriodicCallback(self.send_data, 1000)
        self.timer.start()

    def on_close(self):
        self.timer.stop()

    def on_error(self, error):
        print("error: ", error)
        self.timer.stop()

    def send_data(self):
        # 向前端发送当前时间
        if len(data)>0:
            try:
                self.write_message(data)
            except Exception:
                pass

# WebSocket服务定义
application = web.Application([
    (r'/', WebSocketHandler),
])

if __name__ == '__main__':
    print("WebSocket服务监听端口：", LISTEN_PORT)
    application.listen(LISTEN_PORT)

    print("启动数据读取服务")
    ioloop.IOLoop.current().run_sync( Trans )

    print("启动WebSocket数据提供服务")
    ioloop.IOLoop.current().start()
